/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */

package com.jav;

import com.jav.bean.Cliente;
import com.jav.bean.Producto;
import com.jav.inter.Constantes;
import com.jav.per.PersisPedido;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.sun.lwuit.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.rms.RecordEnumeration;


public class Datos implements Constantes{

    private Hashtable clientes;
    private Hashtable productos;
    private Vector prodOrd = null;
    private String []CAMPOSCLIENTES = new String[]{"DD","ORDEN","CLIENTE","NOMBRE","APELLIDO","RAZON","DDRR","TELE","NIT","ZONA","COND","CIUDAD","DANE","BARRIO","TIPO"};
    private final String []CAMPOSPRODUCTOS = new String[]{"PROD","DES","PRECIO","PORCIVA","PROV","IMPULSAR","RUTERO"};
    private StringBuffer logs = new StringBuffer();
    private Resources res = null;

    public Resources getRes() {
        if(res == null){
            try {
                res = Resources.open("/res/r.res");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return res;
    }

    public StringBuffer getLogs() {
        return logs;
    }

    public void addLogs(String log) {
        String mns = "********\n"+log+"\n********\n";
        this.logs.insert(0, mns);
    }


    private static Datos _instance;


    private Datos(){ }

    public static Datos getInstance(){
        if(_instance == null){
            _instance = new Datos();
        }
        return _instance;
    }

    public Vector getProdOrd() {
        return prodOrd;
    }

    public void setProdOrd(Vector prodOrd) {
        this.prodOrd = prodOrd;
    }

    public Hashtable getClientes() {
        return clientes;
    }

    public void setClientes(Hashtable clientes) {
        this.clientes = clientes;
    }

    public Hashtable getProductos() {
        return productos;
    }

    public void setProductos(Hashtable productos) {
        this.productos = productos;
    }

    public boolean isVacioCli(){

        if( getClientes() == null){
            return true;
        }
        else{
            return false;
        }
    }

    public boolean isVacioPro(){

        if( getProductos() == null){
            return true;
        }
        else{
            return false;
        }
    }

    public void carClientes (final String url) throws Exception{
        FileConnection  conn  = null;
        DataInputStream input = null;
        if(!isVacioCli()){
            clientes.clear();
        }
        try {
            conn  = (FileConnection) Connector.open(url, Connector.READ);
            input = conn.openDataInputStream();
            int ch;
            String cliente="";
            clientes = new Hashtable();
            while((ch = input.read()) != -1) {
                  char c = (char) ch;
                  if(c != COMILLA_ASCCI){  //si no es comilla
                    cliente += c;
                  }
                  if (ch == ENTER_ASCCI){
                      Cliente ob_cli = new Cliente();                      
                      Hashtable ht = splitCliente(cliente.trim()+SEPA);
                      if (ht == null) {
                          cliente = "";
                          continue;
                      }
                      String dia = (String) ht.get(CAMPOSCLIENTES[0]);
                      String codigo = (String) ht.get(CAMPOSCLIENTES[2]);
                      ob_cli.setDia(dia);
                      ob_cli.setOrden((String) ht.get(CAMPOSCLIENTES[1]));
                      ob_cli.setCodigo(codigo);
                      ob_cli.setNombre((String) ht.get(CAMPOSCLIENTES[3]));
                      ob_cli.setApellido((String) ht.get(CAMPOSCLIENTES[4]));
                      ob_cli.setRazon((String) ht.get(CAMPOSCLIENTES[5]));
                      ob_cli.setDdrr((String) ht.get(CAMPOSCLIENTES[6]));
                      ob_cli.setTel((String) ht.get(CAMPOSCLIENTES[7]));
                      ob_cli.setNit((String) ht.get(CAMPOSCLIENTES[8]));
                      ob_cli.setZona((String) ht.get(CAMPOSCLIENTES[9]));
                      ob_cli.setCond((String) ht.get(CAMPOSCLIENTES[10]));
                      ob_cli.setCiudad((String) ht.get(CAMPOSCLIENTES[11]));
                      ob_cli.setDane((String) ht.get(CAMPOSCLIENTES[12]));
                      ob_cli.setBarrio((String) ht.get(CAMPOSCLIENTES[13]));
                      ob_cli.setTipo((String) ht.get(CAMPOSCLIENTES[14]));

                      cliente = "";
                      clientes.put(dia.toUpperCase()+codigo.toUpperCase(), ob_cli);
                  }

            }
        }
        finally {
            try {
                if (conn != null){
                    conn.close();
                }
                if(input != null){
                    input.close();
                }
            }
            catch (IOException ex) {
                    ex.printStackTrace();
            }
        }
    }

   public Hashtable splitCliente (String cadena){
        Hashtable items = new Hashtable();
        int pos = cadena.indexOf(PATRON);
        int i = 0;

        while (pos >= 0 && i < NUM_COL_CLIENTE){
            String sub = cadena.substring(0, pos).trim();
            if (sub.toUpperCase().equals(CAMPOSCLIENTES[i]))
                break;
            items.put(CAMPOSCLIENTES[i],sub);
            cadena = cadena.substring(pos + PATRON.length());
            pos = cadena.indexOf(PATRON);
            i++;
        }
        if (items.isEmpty() ) return null;

        return items;
    }

      public Hashtable splitProducto (String cadena){
        Hashtable items = new Hashtable();
        int pos = cadena.indexOf(PATRON);
        int i = 0;
        while (pos >= 0 && i < NUM_COL_PRODUCTO){
            String sub = cadena.substring(0, pos).trim();
            if (sub.toUpperCase().equals(CAMPOSPRODUCTOS[i]))
                break;
            items.put(CAMPOSPRODUCTOS[i],sub);
            cadena = cadena.substring(pos + PATRON.length());
            pos = cadena.indexOf(PATRON);
            i++;
        }
        if (items.isEmpty() ) return null;
        
        return items;
    }

   public void carProductos (final String url) throws Exception{
        FileConnection  conn  = null;
        DataInputStream input = null;
        if(!isVacioPro()){
            productos.clear();
            setProdOrd(null);
        }
        try {
            conn  = (FileConnection) Connector.open(url, Connector.READ);
            input = conn.openDataInputStream();
            int ch;
            String prod="";
            productos = new Hashtable();
            while((ch = input.read()) != -1) {
                  char c = (char) ch;
                  if(c != COMILLA_ASCCI){  //si no es comilla
                    prod += c;
                  }
                  //public final String []CAMPOSPRODUCTOS = new String[]{"CODIGO","DESCRIPCION","PRECIO","IVA","PROVEEDOR"};
                  if (ch == ENTER_ASCCI){
                      Producto ob_pro = new Producto();
                      //por nuevo ajuste se agregó: +PATRON porque solo tiene 5 columnas
                      Hashtable ht = splitProducto(prod.trim()+PATRON);
                      if (ht == null) {
                          prod = "";
                          continue;
                      }
                      String codigo = (String) ht.get(CAMPOSPRODUCTOS[0]);
                      ob_pro.setProd(codigo);
                      ob_pro.setDes((String) ht.get(CAMPOSPRODUCTOS[1]));
                      ob_pro.setPrecio((String) ht.get(CAMPOSPRODUCTOS[2]));
                      ob_pro.setPorciva((String) ht.get(CAMPOSPRODUCTOS[3]));
                      ob_pro.setProv((String) ht.get(CAMPOSPRODUCTOS[4]));
                      prod = "";
                      productos.put(codigo.toUpperCase(), ob_pro);
                  }

            }
            if(!isVacioPro()){
                ordenarProductos();
            }
        }
        finally {
            try {
                if (conn != null){
                    conn.close();
                }
                if(input != null){
                    input.close();
                }
            }
            catch (IOException ex) {
                    ex.printStackTrace();
            }
        }
    }

    private void ordenarProductos() {
        Enumeration e =getProductos().elements();
        Vector prodOrd2 = new Vector();
        while (e.hasMoreElements()) {
                Producto p = ((Producto) e.nextElement());
                prodOrd2.addElement(p);
        }
        if (prodOrd2.size() > 0){
                ordenarVector(prodOrd2);
        }
    }

    private void ordenarVector(Vector vec) {

        Producto []arrPro = new Producto[vec.size()];
        vec.copyInto(arrPro);
        int hastai = vec.size();
        int hastaj =  hastai-1;
        for (int i = 0; i < hastai; i++)
        {
            for (int j = 0; j < hastaj; j++)
            {
                int k = Integer.parseInt(arrPro[j].getProd());
                int l = Integer.parseInt(arrPro[j+1].getProd());
                if (k >= l)
                {
                    Producto aux = arrPro[j];
                    arrPro[j] = arrPro[j+1];
                    arrPro[j+1] = aux;
                }
            }
        }

        vec.removeAllElements();
        for (int i = 0; i < arrPro.length; i++) {
            vec.addElement(arrPro[i]);
        }

        setProdOrd(vec);

    }

    public int getMaxPedido(){
        Persistencia p = null;
        int resp = 0;
        try {
            p = new Persistencia(PERS_MAXPEDIDO);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null,null,false);
            while (re.hasNextElement()){
                ByteArrayInputStream bin = new ByteArrayInputStream(re.nextRecord());
                DataInputStream din = new DataInputStream(bin);
                int i = din.readInt();
                bin.close();
                din.close();
                if (i >= resp){
                    resp = i;
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally{
            if (p != null){
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return resp+1;
    }



    public void setMaxPedido(int num) throws IOException {
        Persistencia p = null;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
        try{
            dout.writeInt(num);
            dout.flush();
            Persistencia.delete(PERS_MAXPEDIDO);
            p = new Persistencia(PERS_MAXPEDIDO);
            p.save(bout.toByteArray());

        }
        catch (Exception ex) {
                ex.printStackTrace();
        }
        finally{
            if(dout!= null){
                 dout.close();
            }
            if(bout!= null){
                 bout.close();
            }
        }


    }

    public String getPatch(){
        Persistencia p = null;
        String resp = "";
        try {
            p = new Persistencia(PERS_RUTA);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null,null,false);
            while (re.hasNextElement()){
                ByteArrayInputStream bin = new ByteArrayInputStream(re.nextRecord());
                DataInputStream din = new DataInputStream(bin);
                resp = din.readUTF();
                bin.close();
                din.close();

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally{
            if (p != null){
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return resp;
    }
   public void savePatch(String ruta) throws IOException {
        Persistencia p = null;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
        try{
            dout.writeUTF(ruta);
            dout.flush();

            p = new Persistencia(PERS_RUTA);
            p.save(bout.toByteArray());

        }
        catch (Exception ex) {
                ex.printStackTrace();
        }
        finally{
            if(dout!= null){
                 dout.close();
            }
            if(bout!= null){
                 bout.close();
            }
        }


    }

   public PersisSetup getPersisSetup(){
        Persistencia p = null;
        PersisSetup setup = null;
        try {
            p = new Persistencia(PERS_DATA_SERVER);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                setup = new PersisSetup();
                setup.resurrect(re.nextRecord());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return setup;

   }
}
